package com.tzxs.pay.main.deposit;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.databinding.ViewDataBinding;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.databinding.library.baseAdapters.BR;
import com.baiiu.filter.adapter.MenuAdapter;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.tzxs.pay.R;
import com.tzxs.pay.databinding.ActivityDepositStBinding;
import com.tzxs.pay.databinding.ItemBillAuthorizationBinding;
import com.tzxs.pay.main.base.BaseActivity;
import com.tzxs.pay.main.bill.detail.AutTncActivity;
import com.tzxs.pay.main.bill.detail.AutTradedDetailActivity;
import com.tzxs.pay.main.bill.model.AutBillImp;
import com.tzxs.pay.main.bill.model.AutOrderBean;
import com.tzxs.pay.main.deposit.viewmodel.DepositViewModel;
import com.tzxs.pay.main.gather.SearchAutActivity;
import com.tzxs.pay.util.IAdapter;
import com.tzxs.pay.util.IHolder;
import com.tzxs.pay.util.StatusBarColorSetter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 押金统计
 */
public class DepositStActivity extends BaseActivity<ActivityDepositStBinding> implements IAdapter.ItemNavigator<AutBillImp> {
    private static final String TAG = "DepositStActivity ";
    private DepositViewModel model;
    private int page = 1;//page  页数
    private int pageNum = 10;//page  页面数据数量
    private String timeType = "-1";//代表所有
    private int orderStatus = 0;//订单状态
    private String payType = "";//支付类型
    private String timeStartStr = "";//当timeType为 0 时的自定义开始使用
    private String timeEndStr = "";//结束时间
    //筛选
    private String[] title = {"订单时间", "订单状态", "支付方式"};
    private List<View> contentView;
    private View timeView, orderStatusView, payTypeView;
    //订单时间view
    private TextView allTime, today, yesterday, thisWeek, thisMonth, lastMonth, startTimeView, endTimeView;
    //支付状态
    private TextView allStatus, settmented, backed, canceled, noSettmented;
    //支付方式
    private TextView allPayTypes, alipay, wx, bank;

    @Override
    protected Activity getChildActivity() {

        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_deposit_st;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarColorSetter.setStatusBarColor(this, Color.parseColor("#FAFAFA"));
        dataBinding.depositStToolbar.setTitle("");
        setSupportActionBar(dataBinding.depositStToolbar);
        dataBinding.depositStToolbar.setOnMenuItemClickListener(item -> {
            if (item.getItemId() == R.id.toolbar_menu_search) {
                Intent intent = new Intent(DepositStActivity.this, SearchAutActivity.class);
                startActivity(intent);
            }
            return false;
        });
        model = ViewModelProviders.of(this).get(DepositViewModel.class);
        //初始化筛选框的view
        initContentView();
        dataBinding.setViewModel(model);
        dataBinding.depositStToolbar.setNavigationOnClickListener(v -> onBackPressed());
        dataBinding.depositStRec.setLayoutManager(new LinearLayoutManager(this));
        model.snackBarText.observe(this, s -> {
            if (s != null) {
                Toast.makeText(DepositStActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        });
        //设置筛选菜单
        dataBinding.dropDownMenu.setMenuAdapter(new MenuAdapter() {
            @Override
            public int getMenuCount() {
                return 3;
            }

            @Override
            public String getMenuTitle(int position) {
                return title[position];
            }

            @Override
            public int getBottomMargin(int position) {
                return 0;
            }

            @Override
            public View getView(int position, FrameLayout parentContainer) {
                return contentView.get(position);
            }
        });
        dataBinding.depositStRec.setAdapter(new IAdapter<AutBillImp, ViewDataBinding>() {
            @Override
            protected int getLayoutId(int viewType) {
                return viewType;
            }

            @Override
            public int getItemViewType(int position) {
                if (position == 0) {
                    return R.layout.item_atu_header;
                } else
                    return R.layout.item_bill_authorization;
            }

            @Override
            protected void convertListener(@NonNull ViewDataBinding binding) {
                super.convertListener(binding);
                if (binding instanceof ItemBillAuthorizationBinding) {
                    ((ItemBillAuthorizationBinding) binding).setItemNavigator(DepositStActivity.this);
                }
            }

            @Override
            public boolean areItemsTheSame(List<AutBillImp> oldData, List<AutBillImp> data, int oldItemPosition, int newItemPosition) {
                if (oldData.get(oldItemPosition) instanceof AutOrderBean.DataBean && data.get(newItemPosition) instanceof AutOrderBean.DataBean) {
                    return ((AutOrderBean.DataBean) oldData.get(oldItemPosition)).getOut_order_no().equals(((AutOrderBean.DataBean) data.get(newItemPosition)).getOut_order_no());
                } else
                    return super.areItemsTheSame(oldData, data, oldItemPosition, newItemPosition);
            }

            @Override
            public void onBindViewHolder(IHolder<ViewDataBinding> holder, int position) {
                super.onBindViewHolder(holder, position);
                if (getData().get(position) instanceof AutOrderBean.DataBean) {
                    AutOrderBean.DataBean bean = (AutOrderBean.DataBean) getData().get(position);
                    if (holder.binding instanceof ItemBillAuthorizationBinding) {
                        ItemBillAuthorizationBinding binding = (ItemBillAuthorizationBinding) holder.binding;
                        String payStr = null;
                        //订单状态
                        switch (bean.getPay_status()) {
                            case 1:
                                payStr = "等待结算";
                                binding.autState.setTextColor(Color.parseColor("#1F78CF"));
                                break;
                            case 2:
                                payStr = "支付失败";
                                binding.autState.setTextColor(Color.parseColor("#999999"));
                                break;
                            case 3:
                                payStr = "等待支付";
                                binding.autState.setTextColor(Color.parseColor("#27AA30"));
                                break;
                            case 4:
                                payStr = "结算成功";
                                binding.autState.setTextColor(Color.parseColor("#ED433F"));
                                break;
                            case 5:
                                payStr = "已退款";
                                binding.autState.setTextColor(Color.parseColor("#EB9205"));
                                break;
                        }
                        binding.autState.setText(payStr);
                        //支付方式
                        switch (bean.getPay_type()) {
                            case "weixin":
                                binding.autPayIcon.setImageResource(R.drawable.ic_wechat);
                                break;
                            case "alipay":
                                binding.autPayIcon.setImageResource(R.drawable.ic_alipay);
                                break;
                            default:
                                binding.autPayIcon.setImageResource(R.drawable.ic_unionpay);
                                break;
                        }
                    }
                }
            }

            @Override
            protected int getDataBRId(int itemViewType) {
                if (itemViewType == R.layout.item_atu_header) {
                    return BR.head;
                }
                return BR.order_aut;
            }

        });
        //第一次进来获取数据
        getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
        //刷新
        dataBinding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            page = 1;
            //获取数据
            model.getDepositBills(payType, page, pageNum, null, null, timeStartStr,
                    timeEndStr, orderStatus, timeType, () -> {
                    }
            );
            refreshLayout.finishRefresh(1000);
        });
        //加载更多
        dataBinding.refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            ++page;
            model.getDepositBills(payType, page, pageNum, null, null, timeStartStr,
                    timeEndStr, orderStatus, timeType, () -> {
                    }
            );
            refreshLayout.finishLoadMore(1000);
        });
    }

    //初始化筛选下拉框
    @SuppressLint("InflateParams")
    private void initContentView() {
        contentView = new ArrayList<>();
        timeView = getLayoutInflater().inflate(R.layout.pop_order_time, null);
        orderStatusView = getLayoutInflater().inflate(R.layout.pop_order_status, null);
        payTypeView = getLayoutInflater().inflate(R.layout.pop_pay_type, null);
        contentView.add(timeView);
        contentView.add(orderStatusView);
        contentView.add(payTypeView);
        //时间view
        allTime = timeView.findViewById(R.id.fast_choose_all);
        today = timeView.findViewById(R.id.fast_choose_today);
        yesterday = timeView.findViewById(R.id.fast_choose_yesterday);
        thisWeek = timeView.findViewById(R.id.fast_choose_this_week);
        thisMonth = timeView.findViewById(R.id.fast_choose_this_month);
        lastMonth = timeView.findViewById(R.id.fast_choose_last_month);
        startTimeView = timeView.findViewById(R.id.choose_conditions_start);
        endTimeView = timeView.findViewById(R.id.choose_conditions_end);
        allTime.setSelected(true);
        TextView commitTime = timeView.findViewById(R.id.commit_sure);
        //支付状态view
        allStatus = orderStatusView.findViewById(R.id.all);
        settmented = orderStatusView.findViewById(R.id.settlemented);
        backed = orderStatusView.findViewById(R.id.backed);
        canceled = orderStatusView.findViewById(R.id.canceled);
        noSettmented = orderStatusView.findViewById(R.id.no_settlement);
        allStatus.setSelected(true);
        //支付类型view
        allPayTypes = payTypeView.findViewById(R.id.pay_type_all);
        alipay = payTypeView.findViewById(R.id.pay_type_alipay);
        wx = payTypeView.findViewById(R.id.pay_type_wx);
        bank = payTypeView.findViewById(R.id.pay_type_bank);
        allPayTypes.setSelected(true);
        //所有时间
        allTime.setOnClickListener(v -> {
            clearOrderTime();
            timeType = "-1";
            timeStartStr = "";
            clearChooseTime();
            allTime.setSelected(true);
            dataBinding.dropDownMenu.close();
            getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
        });
        //今天
        today.setOnClickListener(v -> {
            clearOrderTime();
            timeType = "1";
            clearChooseTime();
            today.setSelected(true);
            dataBinding.dropDownMenu.close();
            getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
        });
        //昨天
        yesterday.setOnClickListener(v -> {
            clearOrderTime();
            timeType = "2";
            clearChooseTime();
            yesterday.setSelected(true);
            dataBinding.dropDownMenu.close();
            getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
        });
        //本周
        thisWeek.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearOrderTime();
                timeType = "3";
                clearChooseTime();
                thisWeek.setSelected(true);
                dataBinding.dropDownMenu.close();
                getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
            }
        });
        //本月
        thisMonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearOrderTime();
                timeType = "4";
                clearChooseTime();
                thisMonth.setSelected(true);
                dataBinding.dropDownMenu.close();
                getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
            }
        });
        //上月
        lastMonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearOrderTime();
                timeType = "5";

                lastMonth.setSelected(true);
                dataBinding.dropDownMenu.close();
                getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
            }
        });
        //开始时间
        startTimeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timeType = "-1";
                chooseTime(startTimeView, 0);
            }
        });
        //结束时间
        endTimeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timeType = "-1";
                chooseTime(endTimeView, 1);
            }
        });
        commitTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearOrderTime();
                if (TextUtils.isEmpty(startTimeView.getText().toString()) || TextUtils.isEmpty(endTimeView.getText().toString())) {
                    Toast.makeText(DepositStActivity.this, "请输入完整的时间段", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (timeJudge(startTimeView.getText().toString()) > timeJudge(endTimeView.getText().toString())) {
                    Toast.makeText(DepositStActivity.this, "结束时间不能小于开始时间", Toast.LENGTH_SHORT).show();
                    return;
                }
                timeStartStr = startTimeView.getText().toString();
                timeEndStr = endTimeView.getText().toString();
                dataBinding.dropDownMenu.close();
                getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
            }
        });
        //所有状态
        allStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearOrderStatus();
                orderStatus = 0;
                allStatus.setSelected(true);
                dataBinding.dropDownMenu.close();
                getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
            }
        });
        //已结算
        settmented.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearOrderStatus();
                orderStatus = 4;
                settmented.setSelected(true);
                dataBinding.dropDownMenu.close();
                getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
            }
        });
        //已退回
        backed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearOrderStatus();
                orderStatus = 5;
                backed.setSelected(true);
                dataBinding.dropDownMenu.close();
                getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
            }
        });
        //已取消
        canceled.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearOrderStatus();
                orderStatus = 2;
                canceled.setSelected(true);
                dataBinding.dropDownMenu.close();
                getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
            }
        });
        //未结算
        noSettmented.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearOrderStatus();
                orderStatus = 1;
                noSettmented.setSelected(true);
                dataBinding.dropDownMenu.close();
                getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
            }
        });
        //支付类型
        //所有支付类型
        allPayTypes.setOnClickListener(v -> {
            clearPayStatus();
            allPayTypes.setSelected(true);
            payType = "";
            dataBinding.dropDownMenu.close();
            getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
        });
        //支付宝
        alipay.setOnClickListener(v -> {
            Log.d(TAG, "initContentView: 进入支付宝选择");
            clearPayStatus();
            alipay.setSelected(true);
            payType = "901";
            dataBinding.dropDownMenu.close();
            getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
        });
        //微信
        wx.setOnClickListener(v -> {
            Log.d(TAG, "initContentView: 进入微信选择");
            clearPayStatus();
            wx.setSelected(true);
            payType = "905";
            dataBinding.dropDownMenu.close();
            getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
        });
        //银行卡
        bank.setOnClickListener(v -> {
            Log.d(TAG, "initContentView: 进入银行卡选择");
            clearPayStatus();
            payType = "902";
            bank.setSelected(true);
            dataBinding.dropDownMenu.close();
            getData(payType, 1, timeStartStr, timeEndStr, orderStatus, timeType);
        });
    }

    //清空选择时间
    private void clearChooseTime() {
        timeStartStr = "";
        timeEndStr = "";
        startTimeView.setText("");
        endTimeView.setText("");
    }

    //清除所有时间选中项
    private void clearOrderTime() {
        allTime.setSelected(false);
        today.setSelected(false);
        yesterday.setSelected(false);
        thisWeek.setSelected(false);
        thisMonth.setSelected(false);
        lastMonth.setSelected(false);
    }

    //清除订单状态选中状态
    private void clearOrderStatus() {
        allStatus.setSelected(false);
        settmented.setSelected(false);
        backed.setSelected(false);
        canceled.setSelected(false);
        noSettmented.setSelected(false);
    }

    //清除支付状态选中
    private void clearPayStatus() {
        allPayTypes.setSelected(false);
        alipay.setSelected(false);
        wx.setSelected(false);
        bank.setSelected(false);
    }

    //获取数据
    private void getData(String payType, int page, String timeStart, String timeEnd, int payStatus, String timeType) {
        //获取数据
        model.getDepositBills(payType, page, pageNum, null, null, timeStart,
                timeEnd, payStatus, timeType, () ->
                        Log.d(TAG, "onCreate: 获取数据成功"));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.search, menu);
        return true;
    }

    @Override
    public void itemClick(AutBillImp item) {
        if (item instanceof AutOrderBean.DataBean) {
            AutOrderBean.DataBean dataBean = (AutOrderBean.DataBean) item;
            Intent intent;
            if (dataBean.getPay_status() == 1 && dataBean.getUnfreeze_status() == 0) {//订单未结算的情况下跳转
                intent = new Intent(this, AutTncActivity.class);
            } else {
                intent = new Intent(this, AutTradedDetailActivity.class);
            }
            intent.putExtra("orderId", dataBean.getOut_order_no());
            startActivity(intent);
        }
    }

    /**
     * 选择时间
     *
     * @param id 控件id
     */
    private void chooseTime(TextView timeView, int id) {
        Log.d(TAG, "chooseTime: 选择时间:");
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(this, (date, v) -> {
            timeView.setText(getTime(date));
            switch (id) {
                case 0:
                    timeStartStr = getTime(date);
                    break;
                case 1:
                    timeEndStr = getTime(date);
                    break;
            }
        })
                .setType(new boolean[]{true, true, true, true, true, true})
                .isDialog(true)
                .build();
        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);
            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);
            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
            }
            mDialog.show();
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        format.applyPattern("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    //判断时间段选择
    private long timeJudge(String time) {
        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        simpleDateFormat.applyPattern("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = simpleDateFormat.parse(time);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }
}